
import { getDynamicModule } from '@sui/sui';
// 远程remote container urls
const remotesUrls = {

}

/**
* 获取 远程微应用模块名
**/
export function getMFMicroAppModuleName(microApp){
    if( microApp ){
        let name = 'MicroApp';
        if( typeof microApp === 'string' ){
            name = microApp;
        } else if( typeof microApp === 'object' ){
            name = microApp.name || name;
            if( microApp.entry ){
                name = name + '_Entry_' + microApp.entry;
            }
        }
        return name;
    }
}

/**
 * 导入远程mf容器模块
 * @param {*} modulePath 
 * @param {*} packageName
 * @param {*} version 
 * @param {*} filename
 * @returns 
 */
export function importMF(modulePath, packageName, version, filename){
    const index = modulePath.indexOf('/');
    if ( index < 0 ) {
        return new Promise((_, inject)=>{
            inject(`importMF: bad Module Name ${modulePath}, should match pattern 'remoteScope/moduleName`)
        })
    }
    const scope = modulePath.slice(0, index);
    const module = modulePath.slice(index + 1);
    let remote_url = remotesUrls[scope];
    if (!remote_url && typeof window._get_sui_webpack_remote_url === 'function' && packageName ){
        remote_url = window._get_sui_webpack_remote_url( packageName, null, version, filename );
    } 
    if ( !remote_url ) {
        return new Promise((_, inject)=>{
            inject(`importMF: no remote url for "${scope}"`)
        })
    }
    return getDynamicModule(remote_url, scope, module)
}

/**
** 导入远程mf 微应用
** @param {*} microApp
**/
export function importMFApp(scope, microApp){
    const module = getMFMicroAppModuleName(microApp)
    return importMF(`${scope}/${module}`)
}